<template>
  <div class="excel-upload-container">
    <el-page-header content="Excel模板导入"></el-page-header>
    <div class="upload-wrapper">
      <el-upload
        class="upload-dragger"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        accept=".xlsx,.xls"
        :file-list="fileList"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将Excel模板拖拽至此处，或<em>点击选择文件</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          支持.xlsx/.xls格式，文件大小不超过10MB<br />
          建议模板中避免嵌套合并单元格，优先使用基础横向/纵向合并
        </div>
      </el-upload>
      <el-button
        type="primary"
        class="upload-btn"
        :disabled="!fileList.length"
        @click="submitUpload"
      >
        开始解析并进入编辑
      </el-button>
    </div>
    <el-card class="preview-card" v-if="previewVisible">
      <el-card-header>
        <span>Excel模板预览</span>
        <el-button type="text" size="mini" @click="previewVisible = false"
          >关闭</el-button
        >
      </el-card-header>
      <el-card-body>
        <div class="preview-content">
          <el-table
            :data="previewTableData"
            :span-method="previewSpanMethod"
            border
            style="width: 100%"
          >
            <el-table-column
              v-for="col in previewColList"
              :key="col"
              :label="`列${col}`"
              width="120"
            >
              <template #default="scope">
                {{ getPreviewCellValue(scope.row.row, col) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card-body>
    </el-card>
  </div>
</template>

<script>
import { excelParseUtil } from '@/utils/excelUtil'

export default {
  name: 'ExcelUpload',
  data() {
    return {
      fileList: [],
      selectedFile: null, // 新增：存储原生 File 对象
      previewVisible: false,
      previewParseResult: {},
      previewTableData: [],
      previewColList: []
    }
  },
  methods: {
    // 文件选择变化
    handleFileChange(file) {
      this.selectedFile = file.raw; // 新增：存储原生文件
      this.fileList = [file] // 只允许上传一个文件
      console.log('选择的文件:', this.fileList)
    },
    // 提交上传并解析
    // 提交上传并解析
    submitUpload() {
       const file = this.selectedFile; // 用户上传的真实文件
      if (!file) {
        this.$message.warning('请先选择Excel文件')
        return
      }

      this.$loading({ text: '正在解析Excel模板...' })
      console.log('提交上传并解析:', file)
      // 关键：解析真实上传的文件（替换原mock接口调用）
      excelParseUtil
        .parseExcel(file)
        .then((parseResult) => {
          this.$loading().close()
          // 给解析结果补充 templateId（模拟生成唯一ID）
          parseResult.templateId = `TPL_${new Date().getTime()}`
          // 预览相关数据
          this.previewParseResult = parseResult
          this.initPreviewTable()
          this.previewVisible = true
        })
        .catch((err) => {
          this.$loading().close()
          this.$message.error(
            `解析失败：${err.message || 'Excel文件格式错误或内容为空'}`
          )
        })
    },
    // 初始化预览表格
    initPreviewTable() {
      const { cells, merges } = this.previewParseResult
      // 生成列列表
      const colSet = new Set(cells.map((cell) => cell.col))
      this.previewColList = Array.from(colSet).sort((a, b) => a - b)
      // 生成行数据
      const maxRow = Math.max(...cells.map((cell) => cell.row))
      this.previewTableData = Array.from({ length: maxRow }, (_, index) => ({
        row: index + 1
      }))
      // 存储合并规则（用于预览）
      this.previewMerges = merges
    },
    // 预览表格合并单元格方法
    previewSpanMethod({ row, column }) {
      const currentRow = row.row
      const currentCol = column.index + 1 // 列索引从0开始，转为1开始
      const merge = this.previewMerges.find(
        (m) => m.row === currentRow && m.col === currentCol
      )
      if (merge) {
        return {
          rowspan: merge.rowspan,
          colspan: merge.colspan
        }
      }
      return { rowspan: 1, colspan: 1 }
    },
    // 获取预览单元格内容
    getPreviewCellValue(row, col) {
      const cell = this.previewParseResult.cells.find(
        (c) => c.row === row && c.col === col
      )
      return cell ? cell.value : ''
    }
  }
}
</script>

<style scoped>
.excel-upload-container {
  padding: 20px;
}

.upload-wrapper {
  margin: 20px 0;
}

.upload-dragger {
  width: 80%;
  margin: 0 auto;
}

.upload-btn {
  display: block;
  margin: 20px auto;
}

.preview-card {
  margin-top: 20px;
}

.preview-content {
  max-height: 400px;
  overflow: auto;
}
</style>
